import Request from 'luch-request';
const http = new Request();
import store from '@/store'
import {
	router,
	RouterMount
} from '@/router'

/**
 * @description 修改全局默认配置
 * @param {Function}   
 */
http.setConfig((config) => {
	/* config 为默认全局配置*/
	config.baseURL = process.env.VUE_APP_API_URL; /* 根域名 */
	config.header = {
		// "Content-Type": "application/json;charset=UTF-8",
		'authori-zation': `Bearer ${store.state.user.token}`,
	};
	return config
})


/**
 * 请求之前拦截
 */
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	config.header = {
		...config.header,
		'authori-zation': `Bearer ${store.state.user.token}`,
	}
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})


/**
 * 请求之后拦截
 */
http.interceptors.response.use((response) => {
	/* 对响应成功做点什么 可使用async await 做异步操作*/
	// console.log("请求后返回数据:", response)
	if (response.data.status == 410000) {
		if (store.state.user.token) {
			uni.showToast({
				title: '登陆失效',
				icon: "error",
				duration: 2000
			});
			store.dispatch('user/logOut');
			store.dispatch('system/set_clear');
			setTimeout(() => {
				uni.reLaunch({
					url: '/login'
				});
			}, 1500)
		} else {
			store.dispatch('user/logOut');
			store.dispatch('system/set_clear');
			uni.reLaunch({
				url: '/login'
			});
		}
		return
	}

	return response.data
}, (error) => {
	if (error.errMsg == "request:fail") {
		uni.showToast({
			title: '服务器错误',
			icon: "error",
			duration: 2000
		});
		uni.hideLoading();
		return
	}
	/*  对响应错误做点什么 （statusCode !== 200）*/
	if (error.errMsg == "request:fail timeout" || error.errMsg == "request:fail abort statusCode:-1 timeout") {
		uni.showToast({
			title: '请求超时',
			icon: "error",
			duration: 2000
		});
		uni.hideLoading();
		return
	}
	return Promise.reject(error)
})

export default http
